package cn.aticow.springboot.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.log4j.Logger;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

public class NettyServer {
    private static final Logger log  = Logger.getLogger(NettyServer.class);

    /*public static void main(String[] args) throws Exception {
        new NettyServer().start(10084);

    }*/
    public void start(Integer port) throws Exception {
        log.info("Start netty . . .");
        //服务端要建立两个group，一个负责接收客户端的连接，一个负责处理数据传输
        //连接处理group
        EventLoopGroup boss = new NioEventLoopGroup();
        //事件处理group
        EventLoopGroup work = new NioEventLoopGroup();
        //创建ServerBootstrap实例
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss,work)
                //设置将要被实例化的ServerChannel类
                .channel(NioServerSocketChannel.class)
                //设置服务端用于通信的端口号[即服务器用于tcp-ip通讯的端口号]
                .localAddress(new InetSocketAddress(port))
                //设置处理数据的类
                //IdleStateHandler这个类会根据你设置的超时参数的类型和值，
                //循环去检测channelRead和write方法多久没有被调用了，如果这个时间超过了你设置的值，那么就会触发对应的事件，
                //read触发read，write触发write，all触发all[TimeUnit.SECONDS]单位秒
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addLast(new IdleStateHandler(2,2,2, TimeUnit.SECONDS));
                        //SimpleServerHandler该类用于监听，处理数据
                        ch.pipeline().addLast(new SimpleServerHandler());
                    }
                });

        log.info("Loading netty . . .");
        //绑定端口后，开启监听,这里不绑定端口号
        ChannelFuture channelFuture = serverBootstrap.bind().sync();
        if (channelFuture.isSuccess()){
            log.info("Start success ...");
        }
    }
}
